<template>
  <a-modal
    :open="open"
    width="640px"
    :title="formState?.bqbh ? '修改病区' : '新增病区'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    :keyboard="false"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" :colon="false" class="form-style-flex">
      <a-form-item label="区域名称" class="w-1/2" v-bind="validateInfos.wardName">
        <a-input v-model:value="formState.wardName" placeholder="请输入" @blur="onBlur" />
      </a-form-item>
      <a-form-item label="助记码" class="w-1/2" v-bind="validateInfos.zjm">
        <a-input v-model:value="formState.zjm" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="区域类别" class="w-1/2" v-bind="validateInfos.wardTypeCode">
        <SelectItem v-model:value="formState.wardTypeCode" type="DT00019" placeholder="请选择" allow-clear />
      </a-form-item>
      <a-form-item label="顺序号" class="w-1/2" v-bind="validateInfos.outOrder">
        <a-input v-model:value="formState.outOrder" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.memo" placeholder="请输入" :rows="5" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import SelectItem from '@/components/SelectItem'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:open', 'success'])
const formState = ref({
  wardName: '',
  zjm: '',
  wardTypeCode: '',
  outOrder: '',
  memo: ''
})
const rulesState = ref({
  wardName: [{ required: true, message: '请选择区域' }],
  zjm: [{ required: true, message: '请输入助记码' }],
  wardTypeCode: [{ required: true, message: '请选择区域类别' }],
  outOrder: [{ required: true, message: '请输入顺序号' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)

const onOk = async () => {
  await validate()
  const { code, msg } = await post('/operation/opex/doSaveWardInfo', {
    ...formState.value,
    id: props.rowData?.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  resetFields()
  emit('update:open', false)
  emit('success')
}
const onBlur = async (e) => {
  const { data, code, msg } = await post('/common/util/getPinyin', {
    name: e.target.value
  })
  if (code !== 0) return message.error(msg)
  formState.value.zjm = data
}
const onCancel = () => {
  resetFields()
  emit('update:open', false)
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.value = { ...props.rowData }
    }
  }
)
</script>
<style lang="less" scoped>
.ant-form {
  display: flex;
  flex-flow: row wrap;
  min-width: 0;
  :deep(.ant-form-item) {
    .ant-form-item-label {
      width: 90px;
    }
  }
  .ant-picker {
    width: 100%;
  }
}
</style>
